<?php

/**
 * produto actions.
 *
 * @package    Terapia Vital
 * @subpackage produto
 * @author     Foxsis
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class produtoActions extends sfActionsFoxsis
{
  public function executeIndex(sfWebRequest $request)
  {
    return $this->forward('produto', 'list');
  }

	public function executeGrid()
	{
		//Recupero todas as informações necessárias para trabalhar com o grid
		$this->getRequestDataTable();
		$this->data					= ItemTable::consultarProduto($this->filter, $this->order);
		$this->total_data			= count($this->data);
		$this->data					= $this->paginadorDataTable($this->data, $this->page_num, parent::LIMIT_PAGE_DATA_TABLE);

		sfLoader::loadHelpers(array('Tag','Url'));

	    foreach($this->data as $key => &$r)
	    {
	    	$r['st_item'] = ($r['st_item'] == 'S') ? 'SIM' : 'NÃO';
	    	$r['created_at'] = format_datetime($r['created_at'], 'dd/MM/yyyy H:m');
	    	$r['updated_at'] = format_datetime($r['updated_at'], 'dd/MM/yyyy H:m');
	    	$actions = array(
				'edit'	 => link_to(
	    			' ',
	    			url_for($this->getModuleName().'/edit?id_item='.$r['id_item']),
	    			array(
	    				'class' => 'icoEditar'
	    			)
	    		),
				'show'	 => link_to(
	    			' ',
	    			url_for($this->getModuleName().'/show?id_item='.$r['id_item']),
	    			array(
	    				'class' =>  'icoVisualizar'
	    			)
	    		),
				'delete' => link_to(
	    			' ',
	    			url_for($this->getModuleName().'/delete?id_item='.$r['id_item']),
	    			array(
	    				'class' => 'icoExcluir delete',
	    				'rel' => url_for($this->getModuleName().'/grid')
	    			)	
	    		)
			);
			$r['act'] = implode(' ', $actions);
    	}

		$this->setJSONDataTable($this->data, $this->colunas, $this->total_data);
		return sfView::NONE;
	}


    public function executeList()
    {
        $this->form = new ItemForm();
    	$this->colunas	= array(
          	$this->form['id_item']->renderLabel() => "id_item",
      		$this->form['nm_item']->renderLabel() => "nm_item",
      		$this->form['st_item']->renderLabel() => "st_item",
      		$this->form['created_at']->renderLabel() => "created_at",
      		$this->form['updated_at']->renderLabel() => "updated_at",
			"Ações"	=> "act"
		);

        $this->filter = $this->_getFilter();
        $this->setTemplate('index');
    }

    public function executeFilter()
	{
	    $filter = new Filtro(
			$this->getRequestParameter(sfActionsFoxsis::FILTER_SESSION_USER_ATTRIBUTE)
		);

		$filter->setCulture($this->getUser()->getCulture());
		$this->getUser()->setAttribute('pg_num',1,$this->getModuleName());
		$this->getUser()->setAttribute(
			sfActionsFoxsis::FILTER_SESSION_USER_ATTRIBUTE,
			serialize($filter),
			$this->getModuleName()
		);

		return $this->forward($this->getModuleName(), '/list');
	}

	public function executeShow(sfWebRequest $request)
	{
		$this->item = Doctrine::getTable('Item')->find(array($request->getParameter('id_item')));
		$this->forward404Unless($this->item);
	}

	public function executeNew(sfWebRequest $request)
	{
		$this->produto = new Item();
		$this->produto->setIdTipo(Tipo::PRODUTOS);
		$this->form = new ItemForm($this->produto);
	}

	public function executeCreate(sfWebRequest $request)
	{
		$this->forward404Unless($request->isMethod(sfRequest::POST));
		$this->form = new ItemForm();
		$this->processForm($request, $this->form);
		
		$this->forward($this->getModuleName(), 'new');
	}

	public function validateCreate()
	{
		return true;
	}

	public function handleErrorCreate()
	{
		return $this->forward($this->getModuleName(), 'new');
	}

	public function executeEdit(sfWebRequest $request)
	{
		$this->forward404Unless($item = Doctrine::getTable('Item')->find(array($request->getParameter('id_item'))), sprintf('Object item does not exist (%s).', $request->getParameter('id_item')));
		$this->form = new ItemForm($item);
	}

	public function executeUpdate(sfWebRequest $request)
	{
		$this->forward404Unless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT));
		$this->forward404Unless($item = Doctrine::getTable('Item')->find(array($request->getParameter('id_item'))), sprintf('Object item does not exist (%s).', $request->getParameter('id_item')));
		$this->form = new ItemForm($item);

		$this->processForm($request, $this->form);

		$this->forward($this->getModuleName(), 'edit');
	}

	public function validateUpdate()
	{
		return true;
	}

	public function handleErrorUpdate()
	{
		return $this->forward($this->getModuleName(), 'edit');
	}

	public function executeDelete(sfWebRequest $request)
	{
		try
		{
			$request->checkCSRFProtection();
			$item = Doctrine::getTable('Item')->find($request->getParameter('id_item'));
			$this->forward404Unless($item, sprintf('Object item does not exist (%s).', $request->getParameter('id_item')));
			
			$sql = "id_item = " . $item->getIdItem();
			
			// Pesquisa as categoria relaticionadas em item_categoria
			$itemcategoria = Doctrine::getTable('ItemCategoria')->findBySql($sql);
			foreach($itemcategoria as $ic)
			{
				$ic->delete();
			}
			
			// Pesquisa as imagens relacionadas em midia
			$midias = Doctrine::getTable('Midia')->findBySql($sql);
			foreach($midias as $m)
			{
				$thumb_pre   = sfConfig::get('sf_thumbnail_dir').'/'.$m->getNmMidia();
				if(file_exists($thumb_pre)) 
					unlink(sfConfig::get('sf_thumbnail_dir').'/'.$m->getNmMidia());
					
				$filepath  = sfConfig::get('sf_upload_dir').'/'.$m->getNmMidia();
				if(file_exists($filepath)) 
					unlink(sfConfig::get('sf_upload_dir').'/'.$m->getNmMidia());
					
				$m->delete();
			}
			
			$item->delete();

			$this->redirect('produto/index');
		}
		catch(Excepiton $e)
		{
			$this->getUser()->setFlash('erro', $e->getMessage());
			$this->redirect('produto/index');
		}

	}

	protected function processForm(sfWebRequest $request, sfForm $form)
	{
		try
		{
			$form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
			if ($form->isValid())
			{
				$item = $form->save();
				$this->getUser()->setFlash('mensagem', 'Dados salvos com sucesso.');
				$this->redirect('produto/edit?id_item='.$item->getIdItem());
			}
		    else
		    {
		    	throw new Exception($form->getErrorSchema());
		    }
	    }
	    catch(Exception $e)
		{
			$this->getUser()->setFlash('erro', $e->getMessage());
		}
  	}
}
